<?php
/**
 * Контроллер материалов
 * 
 * Управление матетиалами
 * @author Anton Zavidov
 * @package myLiveShop
 */

/**
 * Класс контроллера для управления материалами
 *
 */
class ControllerArticle extends Element{
	/**
	 * Констуктор
	 *
	 * @param string $className имя контроллера
	 */
	public function __construct($className=null){
		$this->name='article';
		parent::__construct($className?$className:__CLASS__);
	}
	/**
	 * Просмотр елемента
	 *
	 */
	public function show($page=false,$model=null){
		$page = $page ? $page : Requestlocal::getInt('page',1);
		parent::show();
		import('model.article');
		$settings=array('where'=>ModelArticle::F_SHOP_ID.'='.Vars::_(Router::SHOP_ID).' AND '.ModelArticle::F_DELETED.'=0 AND '.ModelArticle::F_MODEL.'="'.($model?$model:Requestlocal::getString('model','article')).'"');
		$this->setupPagination($page, $settings);
		$data = $this->model()->load(
			false,
			array(
				ModelArticle::F_ARTICLE_ID,
				ModelArticle::F_TITLE,
				ModelArticle::F_MODEL
			),
			$settings
		);
		if(Core::isJSON() && Requestlocal::getInt('asTable',null)){
		$this->view->setAll($this->view->tablePack($data));
		} else {
			$this->view->set('list', $data);
			$this->setShowPagination();
		}
        $this->build();
	}
	/**
	 * Просмотр елемента
	 *
	 */
	public function display(){
		parent::display(true);
		import('model.category');
		$params = array();
		$fields = array(
		  ModelArticle::F_ARTICLE_ID,
		  ModelArticle::F_TITLE,
		  ModelArticle::F_DESCRIPTION,
		  ModelArticle::F_CATEGORY_ID,
		  ModelArticle::F_CREATED,
		  ModelArticle::F_MODEL,
		  ModelArticle::F_IMAGE_ID,
		  ModelArticle::F_SHOP_ID,
		  ModelCategory::TABLE.DOT.ModelCategory::F_TITLE
		);
		$cat=Requestlocal::getInt('category_id',null);
		if($cat != null){
			$params['where'] = ModelCategory::TABLE.DOT.ModelArticle::F_CATEGORY_ID."=".$cat;
		}
		///надо чем то заменить
		if(count($params)){
			$params['where'] =implode(' AND ', $params);
			$article_info = $this->model()->load(false,$fields,$params);
			foreach ($article_info as &$item) {
				$item['shop'] = $this->model('shop')->getName($item[ModelArticle::F_SHOP_ID]);
				$item['tags'] = $this->model()->getAllTags($item[ModelArticle::F_ARTICLE_ID]);
				$item['image'] = import('helper.image',true)->get($item[ModelArticle::F_IMAGE_ID]);
			}
		}else{
			$article_info = $this->model()->loadOne($this->id,$fields,$params);
			$article_info['shop'] = $this->model('shop')->getName($article_info[ModelArticle::F_SHOP_ID]);
			$article_info['image'] = import('helper.image',true)->get($article_info[ModelArticle::F_IMAGE_ID]);
			$article_info['tags'] = $this->model()->getAllTags($article_info[ModelArticle::F_ARTICLE_ID]);
		}		
		$this->view->set('element',$article_info);
		$this->build();
	}
	/**
	 * Просмотр по конкретному пользователю
	 * 
	 */
	public function showByUser(){
		parent::display(false);
		$view='info';
		$user = false;
		if($this->id)$user = $this->id;
		else $user = Requestlocal::getInt('user_id',null);
		if(!$user && isset($_SESSION['user_id'])) $user = $_SESSION['user_id'];
		if($user){
			$this->showBySelector(ModelArticle::TABLE.DOT.ModelArticle::F_USER_ID.'="'.$user.'" AND '.ModelArticle::TABLE.DOT.ModelArticle::F_SHOP_ID."=0");
		} else {
			$this->article_info = false;
		}
		$this->view->set('info',$this->article_info);
		$this->build($view);
	}
	/**
	 * Просмотр по конкретному магазину
	 * 
	 */
	public function showByShop(){
		parent::display(false);
		$view='info';
		$shop = Requestlocal::getString('shop',null);
		if($shop){
			$shop=$this->model('shop')->getId($shop);
		}
		if(!$shop && isset($_SESSION['shop_id'])) $shop = $_SESSION['shop_id'];
		if($shop){
			$this->showBySelector(ModelArticle::TABLE.DOT.ModelArticle::F_SHOP_ID.'="'.$shop.'"');
		} else {
			$this->article_info = false;
		}
		$this->view->set('info',$this->article_info);
		$this->build($view);
	}
	private function showBySelector($selector){
		import('model.category');
		$this->article_info=$this->model()->load(null,false,array(
			'fields' => array(ModelArticle::TABLE.DOT.'*', ModelCategory::TABLE.DOT.ModelCategory::F_TITLE.' AS category_name', '(SELECT COUNT(*) FROM comment WHERE comment.model_id = article.article_id AND comment.model="article") AS comments'),
			'where'=>$selector,
			'join'=>array(
				array('table'=>ModelCategory::TABLE, 'key'=>ModelCategory::F_CATEGORY_ID, 'join_table'=>ModelArticle::TABLE, 'join_field'=>ModelArticle::F_CATEGORY_ID)
		)
		));
		///надо чем то заменить
		foreach ($this->article_info as &$item) {
			$item['image'] = import('helper.image',true)->get($item[ModelArticle::F_IMAGE_ID]);
			$item['tags'] = $this->model()->getAllTags($item[ModelArticle::F_ARTICLE_ID]);
			$item['description'] = substr($item['description'],0,300);
		}
	}
	/**
	 * Форма редактирования
	 *
	 */
	public function edit(){
		parent::edit(true);
		if(!Core::mustLogin()) return false;
		$this->view->set('element',$this->model()->loadOne($this->id,array(
			ModelArticle::F_ARTICLE_ID,
			ModelArticle::F_TITLE,
			ModelArticle::F_DESCRIPTION,
			ModelArticle::F_MODEL,
			ModelArticle::F_PUBLISH,
			ModelArticle::F_CATEGORY_ID
		)));
		$this->build();
	}
	/**
	 * Форма создания
	 *
	 */
	public function add(){
		parent::add();
		if(!Core::mustLogin()) return false;
		$this->build();
	}
	/**
	 * Создание
	 *
	 */
	public function save(){
		parent::save();
		if(!Core::mustLogin()) return false;
        $article_id = Requestlocal::getInt(ModelArticle::F_ARTICLE_ID,null,'post');
        $image_id = Requestlocal::getInt(ModelArticle::F_IMAGE_ID, 0);
        $shop_id = $this->model('shop')->getId(Requestlocal::getString('shop', ''));
        if(!$shop_id) $shop_id = Vars::_(Router::SHOP_ID);
		if($shop_id && !$image_id) $image_id = '0';
		$result=$this->model()->save(
			array(
			    ModelArticle::F_SHOP_ID  		=>$shop_id,
            	ModelArticle::F_USER_ID  		=>Core::user(),
            	ModelArticle::F_LANG_ID  		=>Core::lang(),
            	ModelArticle::F_CATEGORY_ID		=>Requestlocal::getInt(ModelArticle::F_CATEGORY_ID),
            	ModelArticle::F_IMAGE_ID  		=>$image_id,
            	ModelArticle::F_MODEL			=>Requestlocal::getString(ModelArticle::F_MODEL),
            	ModelArticle::F_DELETED			=>0,
            	ModelArticle::F_CREATED			=>Core::date(),
            	ModelArticle::F_PUBLISH			=>Core::setAccess(),
            	ModelArticle::F_SOURCE			=>Requestlocal::getString(ModelArticle::F_DESCRIPTION),//Requestlocal::getString('source'),
            	ModelArticle::F_DESCRIPTION		=>Requestlocal::getString(ModelArticle::F_DESCRIPTION),
				ModelArticle::F_TITLE           =>Requestlocal::getString(ModelArticle::F_TITLE),
			),
			$article_id
		);
        if(is_numeric($result)){
            $article_id = $result;
        }
        if(is_array($result)){
        	$this->view->result($result);
        } else {
        	if($article_id) {
	            //устанавливаем метки
	            import('helper.tag');
	            HelperTag::setTags('article', $article_id, Requestlocal::getString('tag_id','[]','post'));
	        }
        	if($image_id && $image_id!='0' && Requestlocal::getInt('newImage',0)){
            	import('helper.image',true)->setModule($image_id,'article',$article_id);
            } elseif (Requestlocal::getInt('newImage',0)){
            	import('helper.image',true)->deleteImageFromModule('article',$article_id);
            }
        	$this->view->result(false);
        }
	}
	/**
	 * Удаление
	 *
	 */
	public function delete(){
		if(!Core::mustLogin()) return false;
		if(parent::delete(true)){
			F('ControllerComment')->deleteComments('article',$this->id);
			if(Core::isJSON()) {
                $this->view->result();
                return true;
            }
		}elseif(Core::isJSON()) {
            $this->view->result(true);
            return false;
        }
		Core::redirect(base64_decode(Vars::_(Core::REFERER)),T::_('Deleted'));
	}
}